package com.face.shiro;

import java.util.ArrayList;

import java.util.List;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;

import com.face.pojo.SysPermission;
import com.face.pojo.TbTeacher;
import com.face.pojo.TeacherInfo;
import com.face.service.LoginService;

import net.sf.ehcache.config.generator.model.elements.SearchableConfigurationElement;

public class CustomRealm extends AuthorizingRealm {

	@Autowired
	private LoginService loginService;

	// 设置realm的名称
	@Override
	public void setName(String name) {
		super.setName("customRealm");
	}

	// 用于授权
	@Override
	protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {

		TbTeacher TbTeacher = (TbTeacher) principals.getPrimaryPrincipal();

		List<SysPermission> permissionList = null;

		try {
			permissionList = loginService.findPermissionListByTeacherId(TbTeacher.getId());
		} catch (Exception e) {
			e.printStackTrace();
		}

		List<String> permissions = new ArrayList<String>();

		if (permissionList != null) {
			for (SysPermission sysPermission : permissionList) {
				permissions.add(sysPermission.getPercode());
			}
		}
		SimpleAuthorizationInfo simpleAuthorizationInfo = new SimpleAuthorizationInfo();
		simpleAuthorizationInfo.addStringPermissions(permissions);
		return simpleAuthorizationInfo;
	}

	// 用于认证
	@Override
	protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {

		String userCode = (String) token.getPrincipal();
		TbTeacher teacher = null;

		try {
			teacher = loginService.login(userCode);
		} catch (Exception e) {

			e.printStackTrace();
		}
		if (teacher == null) {
			return null;
		}

		// 从数据库查询到密码
		String password = teacher.getPassword();

		// 盐
		String salt = teacher.getSalt();

		// 将info设置simpleAuthenticationInfo
		SimpleAuthenticationInfo simpleAuthenticationInfo = new SimpleAuthenticationInfo(teacher, password,
				ByteSource.Util.bytes(salt), this.getName());

		return simpleAuthenticationInfo;
	}

	// 清除缓存
	public void clearCached() {
		PrincipalCollection principals = SecurityUtils.getSubject().getPrincipals();
		super.clearCache(principals);
	}

}
